package net.sivashov.grailssample.ds

import net.sivashov.grailssample.DataSourceDefinition
import org.apache.commons.dbcp.BasicDataSource
import org.springframework.web.context.request.RequestContextHolder

import javax.sql.DataSource

/**
 * @author LSivashov
 * @since 2/25/13
 */
class DataSourceResolver {
    def static Map<String, DataSource> dataSourceMap = [:]

    def static getDataSource() {
        def datasourceName = ContextHolder.currentDatasourceName

        def ds = dataSourceMap.get(datasourceName)

        if (!ds) {
            def definition = datasourceName ? DataSourceDefinition.findByName(datasourceName) : null
            if (definition) {
                ds = createDatasource(definition)
                dataSourceMap << [(datasourceName): ds]
            }
        }
        ds
    }

    def static createDatasource(DataSourceDefinition definition) {

        new BasicDataSource(
                driverClassName: 'com.mysql.jdbc.Driver',
                url: definition.datasourceUrl,
                username: definition.username,
                password: definition.password
        )
    }


}
